<?php

class MailTemplateController extends CController {
	public $baseUrl;
	public $isSettings;
	public $login;
	public $title;
	public $mailTemplates;
	public $categories;

	public function init() {
		$this->baseUrl = Yii::app()->request->baseUrl;
		$this->isSettings = true;
		$session = new CHttpSession;
		$session->open();
		$this->login = $session['login'];
		$session->close();

		$groups = Yii::app()->db->createCommand("SELECT DISTINCT `group` FROM `settings` ORDER BY `group`")->queryAll();

		$this->title = 'Настройки';
		$this->categories = array(
				'index' => array('title' => 'Все', 'url' => '/admin/settings/'),
				'mail' => array('title' => 'Шаблоны уведомлений', 'url' => '/admin/mailtemplate/', 'active' => 'true'),
		);
		foreach ($groups as $group) {
			$this->categories[$group['group']] = array('title' => $group['group'], 'url' => '/admin/settings?group=' . $group['group']);
		}
		
		$this->mailTemplates = MailTemplate::model()->findAll();
	}

	public function actionIndex() {
		$data = array();
		
		$this->render('index', $data);
	}

	public function actionSave($id) {
		$record = MailTemplate::model()->findByPk($id);
		$record->attributes = $_POST;
		$record->save();
		$this->redirect($this->baseUrl . '/admin/mailTemplate');
	}

	public function uploadImage($file, $directory) {
		$date = date('YmdHis');
		$i = rand(1, 100000);
		$ext = end(explode(".", $file['name']));
		move_uploaded_file($file['tmp_name'], 
		realpath(dirname(__FILE__)) . "/../../../../userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext);
		return "/userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext;
	}
}